/*
 * Copyright (c) 2015 Minshenglife. All rights reserved. Minshenglife
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.sentry.commons.dal;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Optional;



/**
 * 所有service接口的的抽象基类，预定义了一些常用的CRUD操作<br>
 * 一般情况下不要覆盖此基类的方法。
 * 
 * @author WuBo (wub1@minshenglife.com)
 * 
 */
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public abstract class AbstractService<T, PK extends Serializable> {


    public Iterable<T> findAll(Sort sort) {
        return getEntityDao().findAll(sort);
    }

    public Page<T> findAll(Pageable pageable) {
        return getEntityDao().findAll(pageable);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public T save(T entity) {
        return getEntityDao().save(entity);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public Iterable<T> save(Iterable<T> entities) {
        return getEntityDao().save(entities);
    }

    public boolean exists(PK id) {
        return getEntityDao().exists(id);
    }

    public Iterable<T> findAll() {
        return getEntityDao().findAll();
    }

    public Iterable<T> findAll(Iterable<PK> ids) {
        return getEntityDao().findAll(ids);
    }

    public long count() {
        return getEntityDao().count();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void delete(PK pk) {
        getEntityDao().delete(pk);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void delete(T entity) {
        getEntityDao().delete(entity);
    }


    @Transactional(propagation = Propagation.REQUIRED)
    public void delete(Iterable<T> entities) {
        getEntityDao().delete(entities);
    }


    public Optional<T> findOne(PK pk) {
        return Optional.ofNullable(getEntityDao().findOne(pk));
    }

    public abstract PagingAndSortingRepository<T, PK> getEntityDao();


}
